/*
 * Copyright (C) 2017 Pingan, Inc. All Rights Reserved.
 */

package com.pingan.haofang.searchcloud.es.api;

import com.pingan.haofang.searchcloud.api.IndexDataPacket;
import com.pingan.haofang.searchcloud.api.IndexDataPushService;
import com.pingan.haofang.searchcloud.api.constants.EngineType;
import com.pingan.haofang.searchcloud.api.route.IndexRoute;
import com.pingan.haofang.searchcloud.api.route.IndexRouteRegisterFactory;
import com.pingan.haofang.searchcloud.es.indices.IndicesDataService;
import com.pingan.haofang.searchcloud.es.utils.EsUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * es索引构建
 *
 * @author zhangbi617
 * @date 2017-07-06
 */
@Service
public class ElasticIndexPushService implements IndexDataPushService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ElasticIndexPushService.class);

    @Autowired
    private IndicesDataService indicesDataService;

    @Override
    public boolean repository(String host, IndexDataPacket indexDataPacket,
                              int millisecondTimeOut, boolean needRoute) {

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(">>repository,params: indexDataPacket{}, needRoute", indexDataPacket);
        }


        // 1、从数据包中获取 索引名称（其实是collectionName）
        String indexName = indexDataPacket.getIndexName();

        // 2、根据索引名称获取 存储层数据落地的索引
        String enableIndexName = indexName;

        if (needRoute) {
            IndexRoute route = IndexRouteRegisterFactory.get().discover(indexName);
            enableIndexName = route.getCollectionName();
        }

        enableIndexName = EsUtils.nameWithPrefix(enableIndexName);
        try {
            indicesDataService.bulkUpdate(host, enableIndexName, enableIndexName.substring(0,enableIndexName.lastIndexOf("_")), indexDataPacket);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }

        return true;
    }

    /**
     * 获取索引指定字段 最大值
     *
     * @param host
     * @param indexName
     * @param versionField
     * @return 整形的返回值
     */
    @Override
    public Long getMaxValue(String host, String indexName, String versionField){
        return indicesDataService.getMaxValue(host,indexName,versionField);
    }


    @Override
    public EngineType getEngineType() {
        return EngineType.ES;
    }
}
